package org.WhyMCA.NetManager;

/**
@author Danilo '' Riso >> danilo DOT riso AT gmail DOT com
* @author Androidiani Dev Team
* @version 1.0
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import org.WhyMCA.NetManager.URLManager;

import android.os.Handler;
import android.os.Message;

public class NetworkMgr implements Runnable {

	private static Thread _netth;
	private static int _state;
	private static String _sbuff = null;
	private static InputStream data;
	private static Handler _hand;
	private static boolean _connerr = false, _connclose = false;
	private static requestCallback cback;
		
	public NetworkMgr() {
		
		createHandler();
		
	}
		
	public interface requestCallback {
	
		public void onRequestStart();
		public void onRequestStop(boolean result);
			
	}
	
	public void setCallBack(final requestCallback callback) {
		
		cback = callback;
		
	}
	
	public void resetBuff() {

		_sbuff = new String();
		
	}
	
	public String getBuff() {

		return _sbuff;
		
	}
			
	public void doRequest() {
		
		_connerr = false;
						
		cback.onRequestStart();
		_netth = new Thread(this);
		_netth.start();
		
	}
	
	public static void setState(int i) {
		
		_state = i;
		
	}
	
	public static int getState() {
		
		return _state;
		
	}
	
	/*private static void checkStatusCode() {
		
		if(_statusCode != 200) {
			
			_connerr = true;
			System.out.println("Non ci sono");
			
		}
		
		if (_statusCode == 200) {
			
			_connerr = false;
															
			System.out.println("Ci sono");
			System.out.println(_sbuff);
														
			checkReturn();
			System.out.println(_sbuff);
			_connclose = true;
			
		}
		
	}*/
	
	public static String doPost() throws IOException {
				
		if(cback == null)
			
			return null;
		
		try {
			
			URI _url = new URI(URLManager.getURL());
			DefaultHttpClient client = new DefaultHttpClient();
			
			HttpGet httpget = new HttpGet(_url);
			httpget.setHeader("Content-Type", "Content-Type: text/html;charset=utf-8");
			HttpResponse res = client.execute(httpget);
			data = res.getEntity().getContent();
			_sbuff = generateString(data);
											
		} catch(ClientProtocolException e) {
			
			e.printStackTrace();
			_connerr = true;
			_connclose = true;
									
		} catch (URISyntaxException e) {
			
			e.printStackTrace();
			_connerr = true;
			_connclose = true;
									
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
			_connerr = true;
			_connclose = true;
									
		} catch (SocketException e) {
			
			e.printStackTrace();
			_connerr = true;
			_connclose = true;
									
		}
		
		return _sbuff;
        
    } 
	
	/*private static void closeChannel() {
				
		try {
			if(_rr != null && _wr != null) { 
				
				_rr.close();
				_wr.close();
				
			}
			//con.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private static void writeChannel() {
		
		try {
			_wr.write(URLManager.getURL());
			_wr.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NullPointerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
	}*/
	
	/*private static void openChannel() {
		
		try {
				
			_wr = new OutputStreamWriter(con.getOutputStream());
			
			//wr.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	private static void checkReturn() {
		
		int c;
		
		_sbuff = new String();
		
		try {
			
			if(_rr != null) {
				
				while((c = _rr.read()) != -1) {
					
					_sbuff = _sbuff + StringHandler.convertByteToString((byte)c); 
					//System.out.println(StringHandler.convertByteToString((byte)c));
					
				}
				
			}
									
			//_hand.sendEmptyMessage(0);
			_connclose = true;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}*/
			
	public static String generateString(InputStream stream) {

		   //InputStreamReader reader = new InputStreamReader(stream, Charset.forName("ISO-8859-1"));
		   InputStreamReader reader = new InputStreamReader(stream, Charset.forName("UTF-8"));
		   BufferedReader buffer = new BufferedReader(reader);
		   StringBuilder sb = new StringBuilder();
		   
		   try {

		   String cur;

		   while ((cur = buffer.readLine()) != null) {

		   sb.append(cur + "\n");

		  }

		  } catch (IOException e) {

		  // TODO Auto-generated catch block

			  e.printStackTrace();

		  	}

		  try {

			  stream.close();

		  } catch (IOException e) {

		  // TODO Auto-generated catch block

			  e.printStackTrace();

		  	}

		  return sb.toString();

		  }

	public void stopConn() {
		
		_connclose = true;
		
	}
	
	private void createHandler() {
		
		_hand = new Handler() {

			@Override

			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				
				Thread _netthstop = _netth;
				_netth = null;
				
				if(_netthstop != null) {
				
					_netthstop.interrupt();
					
				}
				
				System.out.println(_connerr);
				cback.onRequestStop(_connerr);
				//_sbuff = null;
																
			}

			};

		
	}
			
	@Override
	public void run() {

		//Looper.prepare();
				
		try {
			
			while((_sbuff = doPost()) == null && (!_connerr || !_connclose)) {
			
								
			}
										
		} catch (IOException e) {
		
			e.printStackTrace();
			
		}
							
				_hand.sendEmptyMessage(0);
															
	}

}